const { DataTypes } = require('sequelize')
const sequelize = require('../config/database')

const PermissionTemplate = sequelize.define('PermissionTemplate', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    comment: '模板ID'
  },
  name: {
    type: DataTypes.STRING(50),
    allowNull: false,
    comment: '模板名称'
  },
  code: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true,
    comment: '模板编码'
  },
  description: {
    type: DataTypes.STRING(200),
    allowNull: true,
    comment: '模板描述'
  },
  permissions: {
    type: DataTypes.JSON,
    allowNull: false,
    comment: '权限配置（JSON格式）'
  },
  is_system: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false,
    comment: '是否系统预设'
  },
  status: {
    type: DataTypes.TINYINT,
    allowNull: false,
    defaultValue: 1,
    comment: '状态（1正常 0停用）'
  }
}, {
  tableName: 'permission_templates',
  timestamps: true,
  paranoid: true,
  indexes: [
    {
      unique: true,
      fields: ['code']
    }
  ]
})

// 延迟设置关联关系，避免循环依赖
setTimeout(() => {
  const Department = require('./department')
  const UserPermission = require('./userPermission')

  // 与部门的关联关系
  PermissionTemplate.hasMany(Department, {
    foreignKey: 'template_id',
    as: 'departments'
  })

  // 与用户权限的关联关系
  PermissionTemplate.hasMany(UserPermission, {
    foreignKey: 'template_id',
    as: 'userPermissions'
  })
}, 0)

// 创建系统预设模板
PermissionTemplate.createSystemTemplates = async () => {
  const templates = [
    {
      name: '最高权限模板',
      code: 'super_admin_template',
      description: '系统超级管理员的权限模板',
      permissions: {
        system: ['*'],
        business: ['*'],
        data: {
          scope: 'all',
          fields: ['*']
        }
      },
      is_system: true,
      status: 1
    },
    {
      name: '部门管理模板',
      code: 'dept_admin_template',
      description: '部门管理员的权限模板',
      permissions: {
        system: ['view', 'add', 'edit', 'delete'],
        business: ['view', 'export', 'import'],
        data: {
          scope: 'department',
          fields: ['*']
        }
      },
      is_system: true,
      status: 1
    },
    {
      name: '普通用户模板',
      code: 'normal_user_template',
      description: '普通用户的权限模板',
      permissions: {
        system: ['view'],
        business: ['view'],
        data: {
          scope: 'self',
          fields: ['basic']
        }
      },
      is_system: true,
      status: 1
    }
  ]

  for (const template of templates) {
    await PermissionTemplate.findOrCreate({
      where: { code: template.code },
      defaults: template
    })
  }
}

module.exports = PermissionTemplate 